﻿using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
using Microsoft.Win32;
using MessageBox = System.Windows.Forms.MessageBox;

namespace WordStat
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            var dataSrv = new ArticleService();
            _treeGridControl.SetArticleService(dataSrv);
        }

        private void close_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void OpenCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var fileDialog = new OpenFileDialog();

            var res = fileDialog.ShowDialog();

            if (!res.Value)
                return;

            if (!File.Exists(fileDialog.FileName))
                return;

            var fi = new FileInfo(fileDialog.FileName);

            var d = fi.Length / 1024;
            d /= 1024;

            if (d > 1)
            {
                MessageBox.Show("File is too large to open in WordStat");
                return;
            }

            var location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            var dataPath = Path.Combine(location, DATA_PATH);

            if (!Directory.Exists(dataPath))
                Directory.CreateDirectory(dataPath);

            var filePath = Path.Combine(dataPath, Path.GetFileName(fileDialog.FileName));

            if (File.Exists(filePath))
            {
                var tFileName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
                tFileName += Path.GetExtension(fileDialog.FileName);
                filePath = Path.Combine(Path.GetDirectoryName(filePath), tFileName);
            }

            File.Copy(fileDialog.FileName, filePath);

            var curCursor = Cursor;

            try
            {
                TextFileService.AddFileToDb(fileDialog.FileName);
            }
            finally
            {
                Cursor = curCursor;
            }

            _treeGridControl.UpdateSources();
        }

        public static string DATA_PATH = "data";

        private void EditWordExceptions_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var srv = new WordExceptions.WordExceptionService();
            srv.ShowWizard();
        }

        private void PluginTaskService_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }
    }
}
